package com.example.exam.controller.fileController;

import com.amazonaws.services.s3.model.PutObjectResult;
import com.example.exam.entity.Path;
import com.example.exam.utils.AmazeS3Utils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * @author zhang
 */
@RestController
@RequestMapping("/push")
@Log4j2
@ApiIgnore
public class PushController {
    @Autowired
    private AmazeS3Utils amazeS3Utils;

    @PutMapping("/{filename}")
    public ResponseEntity<String> push(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        log.info("filename:{}", filename);
        String path = Path.DIR_PATH + filename;
        log.info("path:{}", path);
        File file1 = new File(path);
        try {
            if (file1.createNewFile()) {
                file.transferTo(file1);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok("push success");
    }

    @PostMapping("/path")
    public PutObjectResult pushPath(@RequestParam("file") MultipartFile file) throws IOException {
        PutObjectResult po = amazeS3Utils.streamUpload(file.getOriginalFilename(), file.getInputStream());
        log.info("pushPath:{}", po);
        return po;
    }

    @GetMapping("/path")
    public void getPath(@RequestParam("key") String key, HttpServletResponse response) {
        try {
            log.info("文件下载的key={}", key);
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            InputStream inputStream = amazeS3Utils.download(key);
            stopWatch.stop();
            log.info("文件下载执行时间（ms）：{}", stopWatch.getTotalTimeMillis());
            // 处理结果
            if (inputStream != null) {
                response.setContentType("image/jpeg");
                //response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + key);
                OutputStream os = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int len;

                while ((len = inputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                inputStream.close();
                os.close();
                log.info("文件下载：");
            }
        } catch (Exception e) {
            log.error("文件下载", e);
        }
    }
}

